package com.shop.cloud.controller.system;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.system.SysRole;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.MagicPermission;
import com.shop.cloud.model.request.AddSysRoleRequest;
import com.shop.cloud.model.request.DeleteSysRoleRequest;
import com.shop.cloud.model.request.EditSysRoleRequest;
import com.shop.cloud.model.request.GetSysRoleListRequest;
import com.shop.cloud.model.response.AddSysRoleResponse;
import com.shop.cloud.model.response.DeleteSysRoleResponse;
import com.shop.cloud.model.response.EditSysRoleResponse;
import com.shop.cloud.model.response.GetSysRoleListResponse;
import com.shop.cloud.service.hongfu.impl.ShopService;
import com.shop.cloud.service.system.IRoleResourceService;
import com.shop.cloud.service.system.ISysRoleService;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping(value = "role")
public class SysRoleController extends BaseController {

	private static final Logger logger=Logger.getLogger(SysRoleController.class);
	
	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private IRoleResourceService roleResourceService;
	
	@Autowired
	private ShopService shopService;
	
	@MagicPermission
	@RequestMapping(value = "updateUserRole", method = RequestMethod.POST)
	@ResponseBody
	public Response updateUserRole(HttpServletRequest request,boolean isAdd) {
		if(isAdd){
			sysRoleService.insertUserRole(getParamMap(request));
		}else{
			sysRoleService.removeUserRole(getParamMap(request));
		}
		return ResponseUtil.ok();
	}
	
	
	@MagicPermission
	@RequestMapping(value = "findUserRole", method = RequestMethod.POST)
	@ResponseBody
	public Response findUserRole(Long userId,HttpServletRequest request){
		Map<String, Object> params=getPageMap(request);
		List<SysRole> datas=sysRoleService.find(params);
		List<String> roleIds=sysRoleService.findUserRole(userId);
		List<Map<String, Object>> dataList=new ArrayList<Map<String,Object>>();
		for (int i = 0; i < datas.size(); i++) {
			SysRole role=datas.get(i);
			Map<String, Object> dataMap=new HashMap<String, Object>();
			dataMap.put("id", role.getId());
			boolean hasValue=false;
			for (String roleId : roleIds) {
				if(roleId.equals(role.getId())){
					hasValue=true;
				}
			}
			if (hasValue) {
				dataMap.put("check", true);
			} else {
				dataMap.put("check", false);
			}
			dataMap.put("name", role.getName());
			dataMap.put("createUser", role.getCreateUser());
			dataList.add(dataMap);
		}
		return ResponseUtil.ok(dataList);
	}
	
	@MagicPermission
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	public Response find(@CurrentUserId Long userId,HttpServletRequest request){
		Map<String, Object> params=getPageMap(request);
		Page<SysRole> datas=sysRoleService.page(params);
		return ResponseUtil.ok(datas);
	}
	
//	@MagicPermission
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Response list(HttpServletRequest request, HttpServletResponse response, @RequestBody GetSysRoleListRequest sysRoleListRequest){
	   Map<String, Object> map = new HashMap<String, Object>();
		List<GetSysRoleListResponse> datas = new ArrayList<GetSysRoleListResponse>(); 
		GetSysRoleListResponse data = null;
		List<SysRole> sysRoleList = null;
		SysRole sysRole = null;
		Map<String, Object> params = null;
		int i = 0;
		
		params = new HashMap<String, Object>();
		if(!(sysRoleListRequest.getRole() == null || sysRoleListRequest.getRole().equals(""))) {
			params.put("id", sysRoleListRequest.getRole());
		}
		if(!(sysRoleListRequest.getStart_time() == null || sysRoleListRequest.getStart_time().equals(""))) {
			params.put("startTime", sysRoleListRequest.getStart_time());
		}
		if(!(sysRoleListRequest.getEnd_time() == null || sysRoleListRequest.getEnd_time().equals(""))) {
			params.put("endTime", sysRoleListRequest.getEnd_time());
		}
		if(!(sysRoleListRequest.getPageIndex_() == null || sysRoleListRequest.getPageIndex_().equals(""))){
			params.put("limitStart", (sysRoleListRequest.getPageIndex_()-1)*sysRoleListRequest.getPageSize_());
		}
		if(!(sysRoleListRequest.getPageSize_() == null || sysRoleListRequest.getPageSize_().equals(""))){
			params.put("limitEnd", sysRoleListRequest.getPageSize_());
		}
		if(sysRoleListRequest.getAuthority() !=null){
			
			if(sysRoleListRequest.getAuthority() == 2){
				params.put("authority", sysRoleListRequest.getAuthority());
				params.put("roleIds", sysRoleListRequest.getRoleIds()); 
	        
	        }
		}
        
       

		sysRoleList = sysRoleService.find(params);
		long count = sysRoleService.count(params);
		for(i = 0 ; i < sysRoleList.size() ; i++) {
			data = new GetSysRoleListResponse();
			sysRole = sysRoleList.get(i);
			data.setId(sysRole.getId());
			data.setCreate_time(sysRole.getCreateDate());
			data.setName(sysRole.getName());
			datas.add(data);
		}
		map.put("data", datas);
		map.put("pageCount", count);
		return ResponseUtil.ok(map);
		
//		List<Shop> list=shopService.find(new Shop());
//		return ResponseUtil.ok(list);
	}
	
	//@MagicPermission
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Response update(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditSysRoleRequest editSysRoleRequest){
		
		EditSysRoleResponse editSysRoleResponse = new EditSysRoleResponse();
		SysRole sysRole = null;
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		Long id = 0L;
		
		if(editSysRoleRequest.getId().equals("") ||
		   editSysRoleRequest.getName().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		id = Long.parseLong(editSysRoleRequest.getId());
		
		params = new HashMap<String, Object>();
		params.put("eqname", editSysRoleRequest.getName());
		sysRole = sysRoleService.findOne(params);
		if(sysRole != null) {
			if(sysRole.getId() != id) {
				return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "名称已存在");
			}
		}
		
		params = new HashMap<String, Object>();
		params.put("id", id);
		sysRole = sysRoleService.findOne(params);
		if(sysRole == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "id不存在");
		}
		
		sysRole.setName(editSysRoleRequest.getName());
		sysRole.setUpdateDate(currentTime);
		sysRole.setUpdateUser(String.valueOf(userId));
		
		sysRoleService.update(sysRole);
		
		return ResponseUtil.ok(editSysRoleResponse);
	}
	
	@MagicPermission
	@RequestMapping(value = "insertTwo")
	@ResponseBody
	public Response insertTwo(String removeResourceIds,String insertResourceIds,String roleId){
		sysRoleService.insertTwo(insertResourceIds,roleId);
		return ResponseUtil.ok();
	}
	
	//@MagicPermission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddSysRoleRequest addSysRoleRequest){
		AddSysRoleResponse addSysRoleResponse = new AddSysRoleResponse();
		SysRole sysRole = null;
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		
		if(addSysRoleRequest.getName().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		params = new HashMap<String, Object>();
		params.put("name", addSysRoleRequest.getName());
		sysRole = sysRoleService.findOne(params);
		if(sysRole != null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "已存在此名称");
		}
		
		sysRole = new SysRole();
		sysRole.setName(addSysRoleRequest.getName());
		sysRole.setRemark(addSysRoleRequest.getName());
		sysRole.setCreateUser(userId);
		sysRole.setUpdateUser(String.valueOf(userId));
		sysRole.setCreateDate(currentTime);
		sysRole.setUpdateDate(currentTime);
		if(!sysRoleService.insert(sysRole)) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
		}
		
		return ResponseUtil.ok(addSysRoleResponse);
	}

 	//@MagicPermission
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Response delete(@CurrentUserId Long userId,HttpServletRequest request, HttpServletResponse response, @RequestBody DeleteSysRoleRequest deleteSysRoleRequest){
 		DeleteSysRoleResponse deleteSysRoleResponse = new DeleteSysRoleResponse();
 		HashMap<String, Object> param= new HashMap<String, Object>();
		param.put("id", deleteSysRoleRequest.getId());
		SysRole r = sysRoleService.find(param).get(0);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", r.getId());
		Long roleId = r.getId();
		System.out.println(sysRoleService.findRole(roleId).size());
		if(sysRoleService.findRole(r.getId()).size()>0){
			return ResponseUtil.error("有账户正在使用此角色类型，无法删除！");
		}else{
			sysRoleService.removeUserRole(map);
			roleResourceService.remove(map);
			sysRoleService.remove(param);
		}
		return ResponseUtil.ok(deleteSysRoleResponse);
	}

}